<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天测试</title>
</head>
<style>
    .msg_send{
        background-color: #fff;
        font-size: 14px;
        float: left;
        clear: both;
        padding: 2px;
        margin: 3px;
    }
    .msg_me{
        background-color: greenyellow;
        font-size: 14px;
        float: right;
        clear: both;
        padding: 2px;
        margin: 3px;
    }
    .msg_div{width: 300px;height: 400px;border:1px solid;background-color: #e2e0e0;overflow-y: auto;}
</style>
<body>
<div>请选择角色：<select id="msg_me">
        <option value="">请选择</option>
        {foreach $users as $key=>$vo }
        <option value="{$vo.id}">{$vo.mobile}</option>
        {/foreach}
    </select>
</div>
<div>请选择聊天对象：<select id="msg_users">
        <option value="">请选择</option>
        {foreach $users as $key=>$vo }
        <option value="{$vo.id}">{$vo.mobile}</option>
        {/foreach}
    </select>
</div>
<div class="msg_div" id="msg_show"></div>
<div style="width: 300px;height: 130px;border-bottom: 1px solid;border-right: 1px solid;border-left: 1px solid;">
    <textarea style="width: 295px;height: 80px" id="msg_get"></textarea>
    <button onclick="connectServer()">连接服务</button>
    <button onclick="send()">发送消息</button>
    <button onclick="send_img()">发送图片</button>
</div>
<input type="file" name="file" id="file" value="选择图片">
<script src="/static/home/js/jquery.min.js"></script>
<script>
    //创建一个socket实例
    var socket = null; //初始为null
    var isLogin = false; //是否登录到服务器上
    var client_id = null;
    var send_uid = null;    // 聊天对象
    var me = null;  // 我自己
    var send_name = null;
    function ajaxPost(url,data,fun) {
        if(!fun){
            fun = function () {};
        }
        $.ajax({
            type: 'POST',
            url: url,
            data: data,
            success: fun,
            dataType: 'json'
        });
    }
    //定义一个连服务的函数
    function connectServer(){
        me = $("#msg_me").val();
        if(!me){
            alert('请选择角色');
            return false;
        }
        send_uid = $("#msg_users").val();
        if(!send_uid){
            alert('请选择聊天对象');
            return false;
        }
        send_name = $("#msg_users").find("option:selected").text();
        console.log(send_name);
        socket = new WebSocket("ws://127.0.0.1:31520");
        socket.onopen = function() {
            console.log('socket onopen');
        };
        socket.onmessage = function(event) {
            console.log(event.data);
            var data = JSON.parse(event.data);
            if(data.code == 'SUCCESS'){
                if(data.data.type == 'connect'){
                    console.log('connect is ok,client_id is:' + data.data.client_id);
                    client_id = data.data.client_id;
                    var url = '/api/msg/server/bindUid';
                    var datas = {
                        sign:'dev',
                        accessKey:'ios',
                        uid:me,
                        client_id:client_id
                    };
                    ajaxPost(url,datas);    // 绑定uid与client_id
                }
                if(data.data.type == 'bind'){
                    console.log('in bind');
                    isLogin = true;
                    var p = document.createElement('p');
                    p.innerHTML = '<span style="color: red;font-size: 14px;">系统:欢迎用户 ' + data.data.uid+"</span>";
                    document.getElementById('msg_show').appendChild(p);
                    $('#msg_show').scrollTop( $('#msg_show')[0].scrollHeight);
                }
                if(data.data.type == 'text'){
                    var p = document.createElement('p');
                    p.innerHTML = '<span class="msg_send">'+send_name+'：' + data.data.msg+"</span>";
                    document.getElementById('msg_show').appendChild(p);
                    $('#msg_show').scrollTop( $('#msg_show')[0].scrollHeight );
                }
                if(data.data.type == 'img'){
                    var p = document.createElement('p');
                    p.innerHTML = '<span class="msg_send">'+send_name+'：<img src="'+data.data.msg+'" width="50"></span>';
                    document.getElementById('msg_show').appendChild(p);
                    $('#msg_show').scrollTop( $('#msg_show')[0].scrollHeight );
                }
            }else{
                alert(data.message);
            }
        };
            // if(/^notice:success$/.test(getMsg)){ //服务器验证通过
            //     isLogin = true;
            // }else if(/^msg:/.test(getMsg)){ //代表是普通消息
            //     var p = document.createElement('p');
            //     p.innerHTML = '<span>收到消息:</span>' + getMsg.replace('msg:','');
            //     document.getElementById('txtcontent').appendChild(p);
            // }else if(/^users:/.test(getMsg)){ //显示当前已登录用户
            //     getMsg = getMsg.replace('users:','');
            //     getMsg= eval('('+getMsg+')'); //转json
            //
            //     var listusers = document.getElementById('listusers');
            //     listusers.innerHTML = '';//清空
            //     for(var key in getMsg){
            //         var option = document.createElement('option');
            //         option.value = key; //ip
            //         option.innerHTML = getMsg[key]; //昵称
            //         listusers.appendChild(option); //添加元素进去
            //     }
            // }
        socket.onclose = function(){
            isLogin = false;
        }
    }
    function send_img() {
        if (!isLogin){
            alert('请先连接服务');
            return false;
        }
        var file = $('#file')[0].files[0];
        var src = window.URL.createObjectURL(file); // 转换为本地可预览的路径
        if(!file){
            alert('请先选择要发送的图片');
        }else{
            var p = document.createElement('p');
            p.innerHTML = '<span class="msg_me">我：<img src="'+src+'" width="50"></span>';
            document.getElementById('msg_show').appendChild(p);
            $('#msg_show').scrollTop( $('#msg_show')[0].scrollHeight );

            var formData = new FormData();
            formData.append('sign','dev');
            formData.append('accessKey','ios');
            formData.append('send_uid',me);
            formData.append('receive_uid',send_uid);
            formData.append('type','img');
            formData.append('msg',file);
            var url = '/api/msg/server/sendMsg';
            $.ajax({
                type: "POST",
                url: url,
                data: formData,
                dataType: "json", //声明成功使用json数据类型回调
                //如果传递的是FormData数据类型，那么下来的三个参数是必须的，否则会报错
                cache: false,  //默认是true，但是一般不做缓存
                processData: false, //用于对data参数进行序列化处理，这里必须false；如果是true，就会将FormData转换为String类型
                contentType: false,  //一些文件上传http协议的关系，自行百度，如果上传的有文件，那么只能设置为false
                success: function () {}
            });
        }
    }
    //发送消息
    function send(){
        if (!isLogin){
            alert('请先连接服务');
            return false;
        }
        var info = document.getElementById('msg_get').value;
        $("#msg_get").val("");
        var p = document.createElement('p');
        p.innerHTML = '<span class="msg_me">我： ' + info+"</span>";
        document.getElementById('msg_show').appendChild(p);
        $('#msg_show').scrollTop( $('#msg_show')[0].scrollHeight );
        var url = '/api/msg/server/sendMsg';
        var datas = {
            sign:'dev',
            accessKey:'ios',
            send_uid:me,
            receive_uid:send_uid,
            type:'text',
            msg:info
        };
        ajaxPost(url,datas);
    }

</script>
</body>
</html>